package com.cakemallproject.controller;

import com.cakemallproject.Util.ControllerUtil;
import com.cakemallproject.pojo.*;
import com.cakemallproject.pojo.mapperObj.Cart;
import com.cakemallproject.pojo.mapperObj.Goods;
import com.cakemallproject.pojo.mapperObj.Type;
import com.cakemallproject.pojo.plusObj.CartDetail;
import com.cakemallproject.service.CartService;
import com.cakemallproject.service.GoodsService;
import com.cakemallproject.service.TypeService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private CartService cartService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private TypeService typeService;

    @GetMapping
    public Result list() {
        log.info("获取购物车列表");
        List<Cart> list = cartService.list();
        return Result.success(list);
    }

    @GetMapping("/{uid}")
    public Result getCartByUid(@PathVariable Integer uid,HttpServletRequest request) {
        log.info("获取用户 {} 购物车信息", uid);
        //验证token
        if (!ControllerUtil.validToken(request)) {
            return Result.error("Invalid_token");
        }
        //获取cart列表
        List<Cart> carts = cartService.getCartByUid(uid);
        //获取goods列表
        List<CartDetail> cartDetails = new ArrayList<>();
        for (Cart cart : carts) {
            Goods goods = goodsService.getById(cart.getGid());
            Type type = typeService.getById(goods.getTid());
            cartDetails.add(new CartDetail(cart,goods,type));
        }
        return Result.success(cartDetails);
    }

    @PostMapping
    public Result addCart(@RequestBody Cart cart) {
        log.info("添加购物车 {}",cart);
        List<Cart> carts = cartService.getCartByUid(cart.getUid());
        for (Cart c : carts) {
            if (c.getGid().equals(cart.getGid())) {
                return Result.error("goods_exist");
            }
        }
        cartService.insert(cart);
        return Result.success();
    }

    @DeleteMapping("/{cartIds}")
    public Result deleteCart(@PathVariable List<Integer> cartIds) {
        log.info("删除购物车 {}",cartIds);
        cartService.delete(cartIds);
        return Result.success();
    }

    @PutMapping
    public Result updateCart(@RequestBody List<Cart> carts ) {
        log.info("更新购物车 {}",carts);
        for (Cart cart : carts) {
            cartService.updateCart(cart);
        }
        return Result.success();
    }
}
